import 'package:flutter/material.dart';
import 'package:flutter_trip/DAO/TripDAO.dart';
import 'package:flutter_trip/Model/TripTabsModel.dart';
import 'package:flutter_trip/TabsPage/TripChannelPage.dart';

class TripPage extends StatefulWidget {
  @override
  _TripPageState createState() => _TripPageState();
}

class _TripPageState extends State<TripPage> with TickerProviderStateMixin {
  TripTabsModel _tripTabsModel;
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 0, vsync: this);
    _loadTripTabsData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          elevation: 0.0,
          backgroundColor: Colors.white,
          title: TabBar(
              controller: _tabController,
              tabs: _tabs(),
              isScrollable: true,
              indicatorSize: TabBarIndicatorSize.label,
              labelColor: Colors.black,
              indicator: UnderlineTabIndicator(
                  borderSide: BorderSide(
                      style: BorderStyle.solid,
                      color: Color(0xff2fcfbb),
                      width: 2),
                  insets: EdgeInsets.only(bottom: 5)))),
      body: TabBarView(controller: _tabController, children: _tabBarListView()),
    );
  }

  void _loadTripTabsData() async {
    TripTabsModel tripTabsModel = await TripDAO.loadTripTabsData();
    setState(() {
      _tripTabsModel = tripTabsModel;
      _tabController =
          TabController(length: _tripTabsModel.tabs.length, vsync: this);
    });
  }

  List<Tab> _tabs() {
    if (_tripTabsModel == null) return [];
    return _tripTabsModel.tabs.map((TripTabItemModel itemModel) {
      return Tab(text: itemModel.labelName);
    }).toList();
  }

  List<Widget> _tabBarListView() {
    if (_tripTabsModel == null) return [];
    return _tripTabsModel.tabs.map((TripTabItemModel itemModel) {
      return TripChannelPage(
          params: _tripTabsModel.params,
          groupChannelCode: itemModel.groupChannelCode);
    }).toList();
  }
}
